package input

import (
	"fmt"
	"reflect"

	"gitee.com/knowgo/ego/core/function"
)

func parseArray(argType *function.ArgumentTypeInfo, data interface{}, fn parseFn) (reflect.Value, error) {
	var info = argType.TypeInfo
	if data == nil {
		// 数据是 nil ，返回空数组
		return reflect.MakeSlice(info.Type, 0, 0), nil
	}
	ary, ok := data.([]interface{})
	if !ok {
		return reflect.ValueOf(nil), fmt.Errorf("cann't parse as slice")
	}

	// itemObj := mgr.Find(rof.Type)
	// if itemObj == nil {
	// 	return reflect.ValueOf(nil), fmt.Errorf("cann't find %s's request'", rof.Name)
	// }
	var count = len(ary)
	slice := reflect.MakeSlice(info.Type, 0, count)
	for n, v := range ary {
		path := fmt.Sprintf("%s[%d]", argType.Name, n)
		// argType.TypeInfo.ReferenceType
		val, err := fn(path, v, argType.ItemType)
		if err != nil {
			return reflect.MakeSlice(info.Type, 0, 0), err
		}
		if info.IsReferenceTypePtr {
			slice = reflect.Append(slice, val)
		} else {
			slice = reflect.Append(slice, val.Elem())
		}
	}
	// 验证合法性
	// 只验证数组元素个数范围
	for _, v := range argType.Validators {
		if err := v.IsValidate(argType.Name, reflect.ValueOf(count)); err != nil {
			return reflect.MakeSlice(info.Type, 0, 0), err
		}
	}

	// 返回切片
	return slice, nil
}
